package main

import (
	"fmt"
	"os"
	"time"

	"gitee.com/mqyqingkong/submit-and-listen/server"
	"github.com/sirupsen/logrus"
)

func main() {
	var logger = &logrus.Logger{
		Out:       os.Stderr,
		Formatter: new(logrus.TextFormatter),
		Hooks:     make(logrus.LevelHooks),
		Level:     logrus.InfoLevel}

	s := server.NewServer(server.WithPort("8181"), server.WithBasePath("/task"),
		server.WithGlobalErrorHandler(func(reqId string, taskPath string, paniced interface{}) error {
			return fmt.Errorf("error occurred: %v", paniced)
		}))
	defer s.Close()
	// 注册任务
	s.RegisterTaskHandler("/batch/test1", sampleHandler{
		logger: logger,
	})
	s.RegisterTaskHandler("/batch/test1Panic", samplePanicHandler{
		logger: logger,
	})
	s.Start()
}

// 定义任务处理类，用于测试
type sampleHandler struct {
	logger *logrus.Logger
}

func (h sampleHandler) Handle(reqId string, params map[string]string) (string, error) {
	h.logger.Infof("Executed success. Received task:%s, task params:%s", reqId, params)
	time.Sleep(2 * time.Second)
	return "process success", nil
}

// 定义任务处理类，用于异常测试
type samplePanicHandler struct {
	logger *logrus.Logger
}

func (h samplePanicHandler) Handle(reqId string, params map[string]string) (string, error) {
	h.logger.Infof("Executed success. Received task:%s, task params:%s", reqId, params)
	time.Sleep(2 * time.Second)
	panic("fail...")
}
